﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Configuration;
using WebMvc.Controllers;
using Common;
using Models;
using System.Web;
using WebMvc.Areas.Models;
using ApiHelperBLL;
using ApiHelperBLL.Models;
using System.Threading.Tasks;
using WebMvc.Filters;
using System.Net.Http.Headers;
using System.IO;
using log4net;

namespace WebMvc.APIControllers
{
    [ApiSecurityFilter]
    public class AlibabaController : BaseApiController
    {
        string appKey = ConfigurationManager.AppSettings["AppKey"].ToString();
        string appSecret = ConfigurationManager.AppSettings["AppSecret"].ToString();
        ILog logWriter = LogManager.GetLogger("AlibabaController");

        #region 美亚体检的账号校验
        /// <summary>
        /// 美亚体检的账号校验
        /// </summary>
        /// <param name="app_key">TOP分配给应用的Appkey</param>
        /// <param name="method">API接口名称</param>
        /// <param name="timestamp">时间戳，格式：yyyy-MM-dd HH:mm:ss</param>
        /// <param name="sign">请求签名，遵守TOP签名规范</param>
        /// <param name="cardId">卡号</param>
        /// <param name="cardKey">密码</param>
        /// <returns></returns>
        public Common.JsonData PostLogin(string app_key, string method, string timestamp, string sign, string cardId, string cardKey)
        {
            logWriter.Info("PostLogin方法进入");
            if (string.IsNullOrEmpty(cardId) || string.IsNullOrEmpty(cardKey))
            {
                return new Common.JsonData() { returnCode = "400", message = "输入参数异常", data = null };
            }
            try
            {
                string pwd = DESEncrypt.Encrypt(cardKey.Trim(), System.Configuration.ConfigurationSettings.AppSettings["decryptkey"]);
                var codepools = oc.BllSession.IBS_CodePoolBLL.Entities.Where(cp => cp.CPName == cardId.Trim() && cp.CPPassword == pwd).ToList();
                if (codepools.Count > 0)
                {
                    BS_CodePool codePool = codepools.FirstOrDefault();
                    string message = string.Empty;
                    if (VerCodePool(codePool, out message))
                    {
                        return new Common.JsonData() { returnCode = "200", message = message, data = new { cardToken = codePool.CPToken } };
                    }
                    else
                    {
                        return new Common.JsonData() { returnCode = "400", message = message, data = null };
                    }
                }
                else
                {
                    return new Common.JsonData() { returnCode = "400", message = "您输入的电子凭证码或密码有误，请重新输入！", data = null };
                }
            }
            catch (Exception ex)
            {
                logWriter.Error("PostLogin" + ex.Message);
                return new Common.JsonData() { returnCode = "500", message = ex.Message, data = null };
            }
        }
        #endregion

        #region 获取卡套餐接口
        /// <summary>
        /// 获取卡套餐接口
        /// </summary>
        /// <param name="app_key">TOP分配给应用的Appkey</param>
        /// <param name="method">API接口名称</param>
        /// <param name="timestamp">时间戳，格式：yyyy-MM-dd HH:mm:ss</param>
        /// <param name="sign">请求签名，遵守TOP签名规范</param>
        /// <param name="cardId">卡号</param>
        /// <param name="cardToken">卡的TOKEN</param>
        /// <returns></returns>
        public JsonList PostPackages(string app_key, string method, string timestamp, string sign, string cardId, string cardToken)
        {
            logWriter.Info("PostPackages方法进入");
            if (string.IsNullOrEmpty(cardId) || string.IsNullOrEmpty(cardToken))
            {
                return new JsonList() { returnCode = "400", message = "输入参数卡号异常", list = null };
            }

            if (string.IsNullOrEmpty(cardToken))
            {
                return new JsonList() { returnCode = "400", message = "输入参数卡Token异常", list = null };
            }

            try
            {
                BS_CodePool codepool = oc.BllSession.IBS_CodePoolBLL.Entities.Where(cp => cp.CPName == cardId.Trim() && cp.CPToken == cardToken.Trim()).FirstOrDefault();
                if (codepool != null && codepool.CPMedicalPackageId != "")
                {
                    //List<int> mpIds=StrHelper.GetIntListByStr(codepools.CPMedicalPackageId);
                    var medicalPackages = oc.BllSession.IBS_MedicalPackageBLL.Entities.Where(mp => mp.MPCode == codepool.CPMedicalPackageCode).Select(mp => new
                    {
                        name = mp.MPName,
                        code = mp.MPCode,
                        sex = mp.MPSex,
                        married = mp.MPMarried
                    }).ToList();
                    return new JsonList() { returnCode = "200", message = "ok", list = medicalPackages };
                }
                else
                {
                    return new JsonList() { returnCode = "400", message = "该卡号没有对应的套餐", list = null };
                }
            }
            catch (Exception ex)
            {
                logWriter.Error("PostPackages" + ex.Message);
                return new JsonList() { returnCode = "500", message = ex.Message, list = null };
            }
        }

        #endregion

        #region 获取套餐详情接口
        /// <summary>
        /// 获取套餐详情接口
        /// </summary>
        /// <param name="app_key">TOP分配给应用的Appkey</param>
        /// <param name="method">API接口名称</param>
        /// <param name="timestamp">时间戳，格式：yyyy-MM-dd HH:mm:ss</param>
        /// <param name="sign">请求签名，遵守TOP签名规范</param>
        /// <param name="cardId">卡号</param>
        /// <param name="cardToken">卡的TOKEN</param>
        /// /// <param name="packageCode">套餐编码</param>
        /// <returns></returns>
        public JsonList PostPackdetail(string app_key, string method, string timestamp, string sign, string cardId, string cardToken, string packageCode)
        {
            logWriter.Info("PostPackdetail方法进入");
            if (string.IsNullOrEmpty(cardId) || string.IsNullOrEmpty(cardToken) || string.IsNullOrEmpty(packageCode))
            {
                return new JsonList() { returnCode = "400", message = "输入参数异常", list = null };
            }
            Token token = (Token)HttpRuntime.Cache.Get(cardId);

            if (string.IsNullOrEmpty(cardToken))
            {
                return new JsonList() { returnCode = "400", message = "输入参数卡Token异常", list = null };
            }
            try
            {
                BS_MedicalPackage medicalPackage = oc.BllSession.IBS_MedicalPackageBLL.Entities.Where(mp => mp.MPCode == packageCode.Trim()).FirstOrDefault();
                if (medicalPackage != null)
                {
                    List<int> mpItems = StrHelper.GetIntListByStr(medicalPackage.MPItems);
                    var medicalItems = oc.BllSession.IBS_MedicalItemBLL.Entities.Where(mi => mpItems.Contains(mi.MIId)).Select(mi => new
                    {
                        checkItemName = mi.MICheckItemName,
                        clinicMeaning = mi.MIClinicMeaning
                    }).ToList();
                    return new JsonList() { returnCode = "200", message = "ok", list = medicalItems };
                }
                else
                {
                    return new JsonList() { returnCode = "400", message = "该套餐没有对应的项目", list = null };
                }
            }
            catch (Exception ex)
            {
                logWriter.Error("PostPackdetail" + ex.Message);
                return new JsonList() { returnCode = "500", message = ex.Message, list = null };
            }
        }

        #endregion

        #region 获取体检机构排期接口
        /// <summary>
        /// 获取体检机构排期接口
        /// </summary>
        /// <param name="app_key">TOP分配给应用的Appkey</param>
        /// <param name="method">API接口名称</param>
        /// <param name="timestamp">时间戳，格式：yyyy-MM-dd HH:mm:ss</param>
        /// <param name="sign">请求签名，遵守TOP签名规范</param>
        /// <param name="cardId">卡号</param>
        /// <param name="cardToken">卡的TOKEN</param>
        /// <param name="hospId">体检机构ID</param>
        /// <returns></returns>
        public async Task<JsonList> PostSchedules(string app_key, string method, string timestamp, string sign, string cardId, string cardToken, string hospId)
        {
            logWriter.Info("PostSchedules方法进入");
            if (string.IsNullOrEmpty(cardId) || string.IsNullOrEmpty(cardToken) || string.IsNullOrEmpty(hospId))
            {
                return new JsonList() { returnCode = "400", message = "输入参数异常", list = null };
            }
            Token token = (Token)HttpRuntime.Cache.Get(cardId);

            if (string.IsNullOrEmpty(cardToken))
            {
                return new JsonList() { returnCode = "400", message = "输入参数卡Token异常", list = null };
            }
            try
            {
                UO_Organization organization = Model_UO_Organization.GetOrgnization(hospId.Trim());
                if (organization != null && !string.IsNullOrEmpty(organization.OrgAPI))
                {
                    Sys_ApiAccount apiAccount = Model_Sys_ApiAccount.GetApiAccountByOrg(organization, "tmall");
                    OrderJsonData orderJsonData = await ApiFactory.CreateResDetailService(apiAccount).GetResList(organization.OrgCheckDept);
                    if (orderJsonData.IsSuccess)
                    {
                        var orderResult = orderJsonData.Content.OrderBy(o => o.checkDate).Select(org => new
                        {
                            strRegdate = org.checkDate.ToString("yyyy-MM-dd"),
                            maxNum = Convert.ToInt32(org.maxRes),
                            usedNum = Convert.ToInt32(org.usedRes)
                        }).ToList();
                        return new JsonList() { returnCode = "200", message = "ok", list = orderResult };
                    }
                    else
                    {
                        return new JsonList() { returnCode = "400", message = orderJsonData.Message, list = null };
                    }
                }
                else
                {
                    return new JsonList() { returnCode = "400", message = "该机构没有对应的预约排期", list = null };
                }
            }
            catch (Exception ex)
            {
                logWriter.Error("PostSchedules" + ex.Message);
                return new JsonList() { returnCode = "500", message = ex.Message, list = null };
            }
        }

        #endregion

        #region 预约单保存接口
        /// <summary>
        /// 预约单保存接口
        /// </summary>
        /// <param name="app_key">TOP分配给应用的Appkey</param>
        /// <param name="method">API接口名称</param>
        /// <param name="timestamp">时间戳，格式：yyyy-MM-dd HH:mm:ss</param>
        /// <param name="sign">请求签名，遵守TOP签名规范</param>
        /// <param name="cardId">卡号</param>
        /// <param name="cardToken">密码</param>
        /// <returns></returns>
        public async Task<Common.JsonData> PostSaveorderinfo(string app_key, string method, string timestamp, string sign, string name, string cardId, string cardToken,
            string idNumber, string contactTel, string married, string sex, string hospId, string regDate, string thirdNum, string packageCode = "")
        {
            logWriter.Info("PostSaveorderinfo方法进入");
            if (string.IsNullOrEmpty(cardId) || string.IsNullOrEmpty(cardToken))
            {
                return new Common.JsonData() { returnCode = "400", message = "输入参数异常", data = null };
            }
            try
            {
                BS_CodePool codepool = oc.BllSession.IBS_CodePoolBLL.Entities.Where(cp => cp.CPName == cardId.Trim() && cp.CPToken == cardToken.Trim()).FirstOrDefault();
                string message = string.Empty;
                packageCode = string.IsNullOrEmpty(packageCode) ? codepool.CPMedicalPackageCode : packageCode;
                var medicalpackage = oc.BllSession.IBS_MedicalPackageBLL.Entities.Where(mp => mp.MPCode == packageCode).FirstOrDefault();
                if (medicalpackage == null)
                {
                    return new Common.JsonData() { returnCode = "400", message = "请勾选合适的套餐！", data = null };
                }
                else
                {
                    if (medicalpackage.MPSex != 2 && !sex.Equals(medicalpackage.MPSex.ToString()))
                    {
                        return new Common.JsonData() { returnCode = "400", message = "该套餐只能" + (medicalpackage.MPSex == 0 ? "女" : "男") + "性可以预约！", data = null };
                    }
                }
                if (VerCodePool(codepool, out message))
                {
                    PE_AppointmentOrder appointmentOrder = GRequestParamaters(cardId, cardToken, name,
                    idNumber, contactTel, married, sex, hospId, packageCode, regDate, thirdNum);

                    Common.JsonData data = await Model_PE_AppointmentOrder.AddAppointmentOrder(appointmentOrder,"tmall");
                    logWriter.Info(data.message);
                    return data;
                }
                else
                {
                    return new Common.JsonData() { returnCode = "400", message = message, data = null };
                }
            }
            catch (Exception ex)
            {
                logWriter.Error("PostSaveorderinfo" + ex.Message);
                return new Common.JsonData() { returnCode = "500", message = ex.Message, data = null };
            }
        }
        #endregion

        #region 预约到检查询接口
        /// <summary>
        /// 预约到检查询接口
        /// </summary>
        /// <param name="app_key">TOP分配给应用的Appkey</param>
        /// <param name="method">API接口名称</param>
        /// <param name="timestamp">时间戳，格式：yyyy-MM-dd HH:mm:ss</param>
        /// <param name="sign">请求签名，遵守TOP签名规范</param>
        /// <param name="cardId">卡号</param>
        /// <param name="orderId">订单号</param>
        /// <returns></returns>
        public Common.JsonData PostFindcheckdataback(string app_key, string method, string timestamp, string sign, string cardId, long orderId)
        {
            logWriter.Info("PostFindcheckdataback方法进入");
            if (string.IsNullOrEmpty(cardId) || orderId == 0)
            {
                return new Common.JsonData() { returnCode = "400", message = "输入参数异常", data = null };
            }
            try
            {

                PE_AppointmentOrder appointmentOrder = Model_PE_AppointmentOrder.FindAppointmentOrder(orderId);
                BS_MedicalPackage medicalPackage = oc.BllSession.IBS_MedicalPackageBLL.Entities.Where(mp => mp.MPCode == appointmentOrder.AOPackageCode).FirstOrDefault();
                if (appointmentOrder != null)
                {
                    var appOrder = new
                    {
                        id = appointmentOrder.AOId,
                        cardId = appointmentOrder.AOCardId,
                        regDate = appointmentOrder.AORegDate,
                        name = appointmentOrder.AOName,
                        sex = appointmentOrder.AOSex,
                        married = appointmentOrder.AOMarried,
                        packageCode = appointmentOrder.AOPackageCode,
                        packageName = medicalPackage.MPName,
                        hospId = appointmentOrder.AOHospId,
                        idCard = appointmentOrder.AOIdNumber,
                        contactTel = appointmentOrder.AOContactTel,
                        workNo = appointmentOrder.AOWorkNo,
                        orderId = appointmentOrder.AOId,
                        reportStatus = appointmentOrder.AOReportStatus
                    };
                    return new Common.JsonData() { returnCode = "200", message = "ok", data = appOrder };
                }
                else
                {
                    return new Common.JsonData() { returnCode = "400", message = "预约到检查询接口失败", data = null };
                }
            }
            catch (Exception ex)
            {
                logWriter.Error("PostFindcheckdataback" + ex.Message);
                return new Common.JsonData() { returnCode = "500", message = ex.Message, data = null };
            }

        }
        #endregion

        #region 用户报告查看授权
        /// <summary>
        /// 用户报告查看授权
        /// </summary>
        /// <param name="app_key">TOP分配给应用的Appkey</param>
        /// <param name="method">API接口名称</param>
        /// <param name="timestamp">时间戳，格式：yyyy-MM-dd HH:mm:ss</param>
        /// <param name="sign">请求签名，遵守TOP签名规范</param>
        /// <param name="cardId">卡号</param>
        /// <param name="orderId">订单号</param>
        /// <returns></returns>
        public Common.JsonData PostFGrantuserreportview(string app_key, string method, string timestamp, string sign, string cardId, string cardToken,
            string name, string contactTel, string idNumber, string note)
        {
            logWriter.Info("PostFGrantuserreportview方法进入");
            if (string.IsNullOrEmpty(cardId) || string.IsNullOrEmpty(cardToken))
            {
                return new Common.JsonData() { returnCode = "400", message = "输入参数异常", data = null };
            }

            try
            {
                var appointmentOrderList = oc.BllSession.IPE_AppointmentOrderBLL.Entities.Where(ao => ao.AOName == name && ao.AOContactTel == contactTel && ao.AOIdNumber == idNumber).ToList();

                if (appointmentOrderList.Count > 0)
                {
                    PE_AppointmentOrder appointmentOrder = appointmentOrderList.FirstOrDefault();
                    appointmentOrder.AOMemo = note;

                    if (Model_PE_AppointmentOrder.EditAppointmentOrder(appointmentOrder))
                    {
                        return new Common.JsonData() { returnCode = "200", message = "ok" };
                    }
                    else
                    {
                        return new Common.JsonData() { returnCode = "400", message = "用户授权失败，订单更新失败" };
                    }

                }
                else
                {
                    return new Common.JsonData() { returnCode = "400", message = "该用户不存在预约信息，不能授权" };
                }
            }
            catch (Exception ex)
            {
                logWriter.Error("PostFGrantuserreportview" + ex.Message);
                return new Common.JsonData() { returnCode = "500", message = ex.Message };
            }
        }
        #endregion

        #region 预约请求参数
        private PE_AppointmentOrder GRequestParamaters(string cardId, string cardToken, string name,
            string idNumber, string contactTel, string married, string sex, string hospId, string packageCode, string regDate, string thirdNum)
        {
            logWriter.Info("GRequestParamaters方法进入");
            DateTime? birthday = null;
            try
            {
                if (IsWhat.IsIDcard(idNumber))
                {
                    if (IDCardValidation.CheckIDCard(idNumber))
                    {
                        birthday = IDCardValidation.GetBirthday(idNumber);
                    }
                }

                PE_AppointmentOrder appointmentOrder = new PE_AppointmentOrder();

                appointmentOrder.AOThirdNum = !string.IsNullOrEmpty(thirdNum) ? thirdNum.Trim() : "";
                appointmentOrder.AOCardId = !string.IsNullOrEmpty(cardId) ? cardId.Trim() : "";
                appointmentOrder.AOName = !string.IsNullOrEmpty(name) ? name.Trim() : "";
                appointmentOrder.AOIdNumber = !string.IsNullOrEmpty(idNumber) ? idNumber.Trim() : "";
                appointmentOrder.AOContactTel = !string.IsNullOrEmpty(contactTel) ? contactTel.Trim() : "";
                appointmentOrder.AOMarried = !string.IsNullOrEmpty(married) ? long.Parse(married.Trim()) : -1;
                appointmentOrder.AOSex = !string.IsNullOrEmpty(sex) ? long.Parse(sex.Trim()) : 2;
                appointmentOrder.AOHospId = !string.IsNullOrEmpty(hospId) ? hospId.Trim() : "";
                appointmentOrder.AOPackageCode = !string.IsNullOrEmpty(packageCode) ? packageCode.Trim() : "";
                appointmentOrder.AOCreateDate = DateTime.Now;
                appointmentOrder.AOBirthday = birthday;
                if (string.IsNullOrEmpty(regDate))
                {
                    appointmentOrder.AORegDate = null;
                }
                else
                {
                    appointmentOrder.AORegDate = DateTime.Parse(regDate.Trim());
                }

                return appointmentOrder;
            }
            catch (Exception ex)
            {
                logWriter.Error("GRequestParamaters" + ex.Message);
                throw ex;
            }
        }
        #endregion

        #region 校验卡号
        private bool VerCodePool(BS_CodePool codePool, out string message)
        {
            try
            {
                var appointmentOrder = oc.BllSession.IPE_AppointmentOrderBLL.Entities.Where(ao => ao.AOCardId == codePool.CPName.Trim() && ao.AOIsdelete == 0).ToList();
                if (appointmentOrder.Count > 0)
                {
                    message = "该卡号已预约不能重复预约！";
                    return false;
                }

                bool flag = false;
                if (codePool.CPStatus == 0 || codePool.CPStatus == 4 || codePool.CPStatus == 1)
                {
                    message = "非法的码信息！(未销售或已作废)";
                }
                else if (codePool.CPStatus == 2)
                {
                    message = "ok";
                    flag = true;
                }
                else
                {
                    if (codePool.CPBalance > 0)
                    {
                        message = "ok";
                        flag = true;
                    }
                    else
                    {
                        message = "卡金额不足!";
                    }
                }
                return flag;
            }
            catch (Exception ex)
            {
                logWriter.Error("VerCodePool" + ex.Message);
                throw ex;
            }
        }
        #endregion

    }
}
